/**
 * @describe : 行程库中使用的修改下拉控件
 * @author :lyou
 * @date :
 * @update:{
        @describe:2.0样式布局升级
        @author:
        @date:2014/12/17
    }
 *
 */
(function () {
    /**
     var cQuery=window.cQuery||{};
     cQuery.jsonpPosCallback=function(){
    var outArray=data.result.split("@");
    for(var i=0;i<outArray.length;i++){
    var innerArray=outArray[i].split("|"),
    hotel;

    hotel=new this.Hotel(innerArray[0],innerArray[1]);
    this.virtualHotel[hotel.name]=hotel;
    }
    };
     cQuery.virtualHotel={};
     cQuery.Hotel=function (id,name,url){
    this.id=id;
    this.name=name;
    this.url=url;
    };
     // [{"City":2,"Country":1,"CityName":"上海","Ename":"Shanghai"}]
     */
    var virtualHotel = {},
        uid = 0;
    function Hotel(id, name, island) {
        this.id = id;
        this.name = name;
        this.island = island;
    };
    /**
     *  地址对象
     * @param {string}
     * @param {number} 国家id
     * @param {string} 城市中文名称
     * @param {string} 城市英文名称
     *
     */
    function Address(city, country, cityName, ename) {
        this.city = city;
        this.country = country;
        this.cityName = cityName;
        this.ename = ename;
    }

    if (!jQuery) {
        throw ("component need jquery up 1.7XX");
    }
    if (!jQuery.widget) {
        throw ("need jquery ui");
    }
    jQuery.widget('ui.mitiselect', {
        version: '2.0',
        id: 'mitiselect',
        addBtn: null,
        showSelect: null,
        autocomplate: null,
        suffeixImg: null,
        result: null,
        $addChilds: null,
        $hidden: null,
        $historyTable: null,
        $el: null,
        options: {
            cityId: 2,
            miti: true,
            url: '',
            inland: true, // true 閸ヨ棄鍞撮敍?false 閸ヨ棄顦?
            hiddenName: 'txtHotelDescOld',
            pagesize: 10,
            spicalData: null,

            // 修改历史
            historyData: null

        },

        _render: function () {

            var self = this,
                hiddenId = "hidden" + uid,
                marTop = "0px",
                addHTML = "<a name='addtion' href=javascript:void(0); style='display:none'>add</a>",
                showHTML = "<div class='destination_box'>    </div>",
                addDom,
                showDom;
            addDom = jQuery(addHTML).insertAfter(jQuery(this)[0].element);
            //showDom = jQuery(showHTML).insertAfter(addDom);
            self.addBtn = jQuery(addDom);
            self.showSelect = jQuery(".destination_box");//jQuery(showDom);
            self.$hidden = jQuery("#" + hiddenId);
            self.addBtn.on('click',self.addSelect);
            self.addBtn.click(jQuery.proxy(this._addSelect, self));
            jQuery(".destination_box").on('click', "i[name='" + self.suffeixImg + "']", { ref: self }, self._removeSelect);


        },

        //@private
        _renderHistoryTable: function () {
            var self = this,
                table;
            if (self.options.historyData) {

                table = "</br><div name='historyTable'><table border=1 style='background-color:#aaa;border: 1px solid #aaa;'>";
                for (var i = 0; i < self.options.historyData.length; i++) {
                    table += "<tr><td>" + self.options.historyData[i].data + "</td><td>" + self.options.historyData[i].date + "</td><td>" + self.options.historyData[i].usename + "</td></tr>";
                }
                table += "</table></div>";
                self.$el.parent().append(table);
                self.$historyTable = self.$el.find("[name='historyTable']").eq(0);
            }

        },

        _initData: function () {
            var self = this;
            self.result = new Object();
            self.result.length = 0;
            self.suffeixImg = "img" + (uid++);
            self.id += (uid++);

        },

        setup: function (str) {
            var arr = str,
                self = this;

            for (var i = 0; i < arr.length; i++) {
                var address;
                address = new Address(arr[i].City, arr[i].Country, arr[i].CityName, arr[i].Ename);
                self.result[arr[i].CityName] = address;
                self.result.length++;
            }
            self._refreshSelect();
        },

        clear: function () {
            var self = this;
            jQuery("img[name='" + self.suffeixImg + "']").each(function () {
                jQuery(this).trigger("click");
            });
        },

        _refreshSelect: function () {
            var self = this;

            for (var r in self.result) {
                if (r !== "length") {

                    //imgHTML = "<div style='float:left;margin-right:5px;'><a target=_blank href=#>" + self.result[r].cityName + "</a>&nbsp<img src='../Content/CSS/RequireCss/image/xx.png' name='" + self.suffeixImg + "'></div>";
                    imgHTML = "<a href='javascript:;'>" + self.result[r].cityName + "<i name='" + self.suffeixImg + "'>&times;</i></a> ";
                    jQuery(self.showSelect).append(imgHTML);
                }
            }

            self.result.length++;
        },
        // [{"City":2,"Country":1,"CityName":"上海","Ename":"Shanghai                                          "}]
        _create: function () {
            var self = this;
            self._initData();
            self._render();
            self.$el = jQuery(self.element);
            self.autocomplate = jQuery(self.element).autocomplete({
                source: function (request, response) {
                    /**
                     //var resUrl = 'http://hotels.ctrip.com/Domestic/Tool/AjaxFindKeyword.aspx?failedCallback=cQuery.jsonpPosFailedCallback&query=cityId:' + self.options.cityId + ' AND (fullname:"' + jQuery(self.element).val() + '"^2 OR keyword:"' + jQuery(self.element).val() + '") AND sourceType:DomesticHotel &return=pinyin,word,ID,type&section=1-' + self.options.pagesize + '&noTotal=true&responseFormat=json&needTokens=true&resultFormat=text&lineSep=@&fieldSep=|&charset=gb2312';
                     //var resUrl = '../MiceOrderDBV2/Handler/CityNameQueryHandler.ashx?cityName=' + encodeURIComponent(self.autocomplate.val());
                     var resUrl = "http://hotels.ctrip.com/Domestic/Tool/AjaxIndexCityNew.aspx?keyword=" + jQuery(self.element).val();
                     */
                    var resUrl = '../TourLine/GetDestCity';
                    jQuery.ajax({
                        type: "post",
                        url: encodeURI(resUrl),
                        dataType: "json",
                        data: { Destination: jQuery(self.element).val() },
                        success: function (data) {
                            response(self._processCallbackData(data));
                        }
                    });
                    //this.city = city;
                    //  this.country = country;
                    //   this.cityName = cityName;
                    //    this.ename = ename;

                    //response(self._processCallbackData({
                    //    Data: [
                    //        { City: 'xx', Contry: 'xxx', CityName: 'xxxx', Ename: 'yyyy' },
                    //        { City: 'zzz', Contry: 'zzz', CityName: 'zzz', Ename: 'zzz' },
                    //        { City: 'a', Contry: 'a', CityName: 'a', Ename: 'a' },
                    //        { City: 'b', Contry: 'b', CityName: 'b', Ename: 'b' },
                    //    ]
                    //}));
                },

                select: function (event, ui) {
                    if (self.options.miti) {
                        self.addBtn.trigger("click");
                    }
                },
                focus: function (event, ui) {
                    if (self.options.miti) {
                        jQuery(this).val(ui.item.label);
                    }
                }
            });
            jQuery(self.autocomplate).focusin(function () {
                if (self.options.miti) {
                    jQuery(this).val("");
                }

            });
            //self._renderHistoryTable();

        },

        _processCallbackData: function (data) {
            var resultArray = [],
                self = this;
            for (var i = 0; i < data.Data.length; i++) {
                var address;
                //"GHIHotel" Hotel
                address = new Address(data.Data[i].City, data.Data[i].Country, data.Data[i].CityName, data.Data[i].Ename);
                virtualHotel[address.cityName] = address;
                resultArray.push(data.Data[i].CityName);
            }
            //console.log(virtualHotel);
            self.options.spicalData = virtualHotel;
            return resultArray;
        },

        _addSelect: function () {
            var self = this,
                imgURL,
                imgHTML;

            if (virtualHotel[self.autocomplate.val()]) {
                if (!self.result[self.autocomplate.val()]) {
                    if (self.options.island) {
                        imgURL = "//hotels.ctrip.com/hotel/" + virtualHotel[self.autocomplate.val()].id + ".html";
                    } else {
                        imgURL = "//hotels.ctrip.com/international/" + virtualHotel[self.autocomplate.val()].id + ".html";
                    }
                    self.result[self.autocomplate.val()] = virtualHotel[self.autocomplate.val()];
                    imgHTML = "  <a href='javascript:;'>" + self.autocomplate.val() + "<i name='" + self.suffeixImg + "'>&times;</i></a>";
                    jQuery(self.showSelect).append(imgHTML);
                    //self._processHidden();
                    self.result.length++;
                } else {
                    alert('相同地址，请重新填写！');
                }


            } else {
                alert("没有您选择的，请重新填写！");
            }
        },

        _removeSelect: function (e) {
            var fatherNode = jQuery(e.currentTarget).parent();
            jQuery(e.currentTarget).remove();
            var key = fatherNode.text().trim();
            delete e.data.ref.result[key];
            fatherNode.remove();
            e.data.ref.result.length--;
            //调用外部的得到行程名称方法
            if (getTourLineName) getTourLineName();
        },

        _remove: function () {

        },

        _destroy: function () {
            this.autocomplate.autocomplate("destroy");

        },

        getResult: function () {
            return this.result;
        }
    });

})();